package com.example.socket.thread;

import com.example.pojo.CollarMsg;
import com.example.pojo.Railing;
import com.example.pojo.RailingWaring;
import com.example.service.collar.RailingService;
import com.example.socket.server.WebSocketUtil;
import com.example.util.RedisUtil;
import com.example.util.TimeUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

/**
 * @author w
 */
@Slf4j
public class SocketDataHandleThread extends Thread {

    private String ip;
    private CollarMsg collarMsg;
    private RailingService railingService;

    public SocketDataHandleThread(String ip,CollarMsg collarMsg,RailingService railingService){
        this.ip=ip;
        this.collarMsg=collarMsg;
        this.railingService=railingService;
    }

    @SneakyThrows
    @Override
    public void run() {
        RedisUtil.putCollarMsg(ip,collarMsg);
        //存入最新数据redis
        RedisUtil.setRecentMsg(ip,collarMsg);

        //判断是否越界，越界就发送警告信息
        Railing outOfBounds = railingService.isOutOfBounds(collarMsg, ip);
        if (outOfBounds!=null){
            log.info(ip+"越界了！");
            RailingWaring railingWaring = new RailingWaring(ip, TimeUtil.getNowTime(), outOfBounds, collarMsg);
            net.sf.json.JSONObject json = net.sf.json.JSONObject.fromObject(railingWaring);
            WebSocketUtil.sendUser(ip,json.toString());
        }

        boolean outTemperatureLimit = railingService.isOutTemperatureLimit(ip, collarMsg);
        if (outTemperatureLimit){
            log.info(ip+"温度异常！");
            RailingWaring railingWaring = new RailingWaring(ip, TimeUtil.getNowTime(), null, collarMsg);
            net.sf.json.JSONObject json = net.sf.json.JSONObject.fromObject(railingWaring);
            WebSocketUtil.sendUser(ip,json.toString());
        }
    }
}
